import Vue from 'vue'
import axios from 'axios'
import router from '@/router'
import qs from 'qs'
import ElementUI from 'element-ui'
// 创建axios实例
const service = axios.create({
  timeout: 1000 * 30,
  // 允许跨域带token
  withCredentials: true,
  //0529地址地址
  baseURL: 'http://shenleyou.cqxishui.top/admin/',
  // baseURL: 'http://127.0.0.1:8889/admin/',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})

// request拦截器
service.interceptors.request.use(
  (config) => {
    config.headers['X-API-TOKEN'] = Vue.$cookies.get('token') ? Vue.$cookies.get('token') : ''
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    //POST请求时转换data
    if (config.method !== 'get') {
      config.data = qs.stringify(config.data)
    }
    // let uri = config.url.replace(config.baseURL, '');
    // const auths = Vue.$cookies.get('auths');
    // if (uri != 'login' && uri != 'outlogin' && auths && !auths.includes(uri)) {
    //   ElementUI.Message({
    //     showClose: true,
    //     message: '没有权限',
    //     type: 'error',
    //     duration: 1600
    //   });
    //   return Promise.reject(new Error('changePassword'));
    // }
    return config
  },
  (error) => {
    return Promise.reject(error)
  })

// response拦截器
service.interceptors.response.use(response => {
  if (response.config.responseType && response.config.responseType === 'blob') {
    return response.data
  }
  if (typeof response != "object" || typeof response.data != "object") {
    return { msg: '请求错误', code: 1001, data: {} }
  }
  if (response && response.data && response.data.code != 1000 && response.data.msg != '') {
    ElementUI.Message({
      showClose: true,
      message: response.data.msg,
      type: 'error',
      duration: 1600
    })
  }
  // token失效、其他地方登录或未登录
  if (response.data && (response.data.code === 1008 || response.data.code == 1003 || response.data.code == 1004 || response.data.code == 1002)) {
    Vue.$cookies.remove('adminInfo')
    Vue.$cookies.remove('token')
    Vue.$cookies.remove('adminInfo')
    router.push({ name: 'login' })
  }
  if (response.data && response.data.code == 1009) {
    //router.push({ name: '403' });
  }
  //如果是登录返回token则存储
  if (response.data && response.data.data && response.data.data.token) {
    Vue.$cookies.set('token', response.data.data.token)
    Vue.$cookies.set('auths', response.data.data.auth)
  }
  // if(response.data.code!=1000){
  //   that.$message.error(response.data.msg);
  //   return false;
  // }
  return response.data
}, error => {
  return Promise.reject(error)
})



export default service
